// TODO:
// params: ORGZ REPO MODULE ASSEMBLY TMARK MACHINEINST

def onemallStages(vlabel, module){
    def icos= "\u26F0" //montain
    def icot= "\u261B" //pointRightBlack +

	node(vlabel) {ansiColor('xterm') {
        wrap([$class: 'BuildUser']) {
			echo "BUILD_USER=${BUILD_USER}"
			// echo "BUILD_USER_FIRST_NAME=${BUILD_USER_FIRST_NAME}"
			// echo "BUILD_USER_LAST_NAME=${BUILD_USER_LAST_NAME}"
			// echo "BUILD_USER_ID=${BUILD_USER_ID}"
			// echo "BUILD_USER_EMAIL=${BUILD_USER_EMAIL}"
			echo "---"
			echo "env.BUILD_USER=${env.BUILD_USER}"
			echo "env.BUILD_USER_FIRST_NAME=${env.BUILD_USER_FIRST_NAME}"
			// echo "env.BUILD_USER_LAST_NAME=${env.BUILD_USER_LAST_NAME}"
			echo "env.BUILD_USER_ID=${env.BUILD_USER_ID}"
			echo "env.BUILD_USER_EMAIL=${env.BUILD_USER_EMAIL}"
		}            
		
		//srcAnay
		stage(icos+'SRC'){ container('git'){ 
			task(icot+'pacakge')
			echo "scm: $module, byUser: ${env.BUILD_USER}"

			// env.PATH = "${tool 'M3'}/bin:${env.PATH}"
			//checkout scm
			// sh "cur=\$(pwd) && mkdir -p \$cur"  && du -sh * 

			//cleanWs
			sh """
				set +x
				pwd && ls -lh && export |grep WORKSPACE
				if [ ! "" == "\$WORKSPACE" ]; then
					! test "/" == "\$WORKSPACE" && rm -rf \$WORKSPACE/* #danger
					echo "WORKSPACE清理完毕!"
				fi
			"""

			dir("/opt/jk_ws/t1") {
				sh """
					set +x
					git config --global user.email "sam@jenkins-v204.6-j9-020"
					git config --global user.name "sam"

					#pwd
					if [ ! -d /opt/jk_ws/t1/clone-src ]; then
						git clone https://gitee.com/g-java/fk-sca-onemall.git clone-src
					else
						cd clone-src && git pull
					fi
				"""
			}
			// sh "ls -lh /opt/jk_ws/"
		}}

		//langBuild: java/go/node/c,c++
		stage(icos+'BUILD'){ container('maven'){ 
			task(icot+'pacakge')
			echo "mvn"
            // sh "echo aa:$module"  //bad: 'echo aa:$module'
			sh """
				set +x
				echo "module:$module"
				cd /opt/jk_ws/t1/clone-src/$module && ls -lh
				
				echo "正在构建，请稍后.."
				#out=/tmp/out1-maven
				#mvn -s ../mvn-settings.xml clean install > \$out #TODO mvn errCode.
				#tail -1 -f \$out |grep "ERROR\\|WARN\\|SUCCESS" #先输出到文件，再tail+grep达实时grep效果 ##1.前一步前加"&"; 2.tail改用loop顺序读取?得识别EOF 退出tail

				mvn -s ../mvn-settings.xml clean install |grep "ERROR\\|WARN\\|SUCCESS"
			"""
            dir("/opt/jk_ws/t1/clone-src"){
                // stash includes: "/opt/jk_ws/t1/clone-src/$module/$module-application/target/*-assembly.tar.gz", name: 'art1'
                stash name: 'art1', includes: "$module/$module-application/target/$module-application-assembly.tar.gz"
            }
		}}

		//TODO: 
		// binary: 提供target-dest压缩包
		// image: 提供target-dest目录, Dockerfile模板
		// 
		// java: 两种选项：做基础包 / 做增量包
		stage(icos+'ARTIFACT'){ container('docker'){ 
			task(icot+'docker-img-build')
			unstash "art1"

			// Lad script from library
			def dockerfile = libraryResource 'templates/dockerfiles/java.Dockerfile'
			writeFile file: './java.Dockerfile', text: dockerfile
			
			// sh "docker version"
			// sh "docker build -t ss1 -f java.Dockerfile ."
			sh """
				set +x #close dbg by jenkins
				repo=onemall
				mkdir -p unpack && tar -zxf $module/$module-application/target/$module-application-assembly.tar.gz -C unpack/ 
				pwd && ls -lh && ls -lh unpack/

				docker_repo_url=registry.cn-shenzhen.aliyuncs.com
				ns=onemall #cp
				tag=latest
				target=\$docker_repo_url/\$ns/\$repo-$module:\$tag
				red1="\033[31m" && red2="\033[0m"
				echo -e ">>>==============={{ \${red1}\$target\${red2} }}>>>build:========================================="
				
				echo "正在构建镜像，请稍后..."
				#vfs="--format=docker --storage-driver=vfs"
				vfs="--format=docker"
				#--pull-always #--pull
				#out=/tmp/out2-buildah
				bh bud \$vfs --pull-always --build-arg TAG=v1.0.2 -t \$target -f java.Dockerfile . 2>&1 |grep -v "Copying" #tail+grep实时
				
				exit 0 #dbg: skip push
				echo "登录仓库并推送镜像，请稍后..."
				set +e
				source /opt/jk_ws/profile-sec #load key
				set -e
				docker_repo_user=\$DOCKER_REGISTRY_USER_demo1ct
				docker_repo_pass=\$DOCKER_REGISTRY_PW_demo1ct
				echo "\${docker_repo_pass}" |bh login --tls-verify=false --username=\${docker_repo_user} --password-stdin \$docker_repo_url

				bh push --tls-verify=false \$target					
			"""
		}}

		// genTpl: sv/dcp/yaml
		// 取tpl模板，注入参数，更新destRepo
		// [tpl_xxx]/sv,dcp,yaml
		stage(icos+'TPL'){ container('tpl'){ 
			task(icot+'template')
			def tplId='01java_springboot'
			// def module="t1-module"

			def templater = libraryResource 'libs/templater.sh'
			writeFile file: './templater.sh', text: templater

			def tplPath1 = libraryResource "templates/layouts/${tplId}.tgz"
			writeFile file: "${tplId}.tgz", text: tplPath1

			// sh "pwd && ls -lh"
			sh """
				set +x
				repo=onemall
				
				if ! [ -x "\$(command -v git)" ]; then #if not installed
					apk add git
				fi
				#clone
				auth=rop2:4b3de1d72e77878dec7b095e0a3c3bf5
				layoutRepo=https://\$auth@gitee.com/infrastlabs/layouts.git
				rm -rf layouts && git clone \$layoutRepo layouts

				#unpack
				dest=tpl && rm -rf \$dest && mkdir -p \$dest
				tar -xf ${tplId}.tgz -C \$dest #tar -zxf: tar -z not suported with busybox.
				ls \$dest/

				#templater
				#dest=layouts/$module && rm -rf \$dest && mkdir -p \$dest
				dest=layouts/$module && mkdir -p \$dest #no delete destDir

				export GENERATE="gen@\$(date '+%Y-%m-%d %H:%M:%S')"
				export IMG_NAME=\$repo-$module
				export IMG_NS="onemall"
				export APP_NAME=\$repo-$module
				sh templater.sh tpl/dcp.yml > \$dest/dcp.yml
				sh templater.sh tpl/k8s.yml > \$dest/k8s.yml
				sh templater.sh tpl/sv.conf > \$dest/sv.conf

				#exit 0
				#commit_push
				git config --global user.name "rop2"
				git config --global user.email "rop2-jk-auto@qq.com"
				cd layouts
				  git add -A .
				  git commit -m "auto@\$(date '+%Y-%m-%d %H:%M:%S')"
				  git push origin master
			"""
		}}

		// deployr/fluxgitops部署编排: sv-binary/dcp:pullGit特定模块 yaml:kube-cmd_ssh;
		// rdeploy.sh文件[type]: binary: stop > backup > clear > unpack > start; img-dcp: stop/down > pull > up; yaml: apply --record
		// destRepo: 环境分支? >> 直接tag标注v1.2.2-dev (环境上的差异不带到编排文件中来| 配置中心) 
		stage(icos+'DEPLOY'){
		container('kubectl'){
			task(icot+'k8s deploy')
			echo "kubectl"
		}}

	}}
}



def call(module) {
    //SRC+BUILD+ARTIFACT+TPL+NOTIFY
 	// /configure: 从 master 传递给 agent 的环境变量; ver: 1.24.1	

    def prefix="maven-"
    def vlabel = "${prefix}${UUID.randomUUID().toString().substring(0,4)}"
    def utils = new com.gitee.infrastlabs.Utils()
    ret = utils.getEmpSlave("${prefix}")
    echo "ret: $ret"
    if ( ret.length() != 0) {
		vlabel = ret
    }

    podTemplate(showRawYaml: false, label: vlabel, cloud: 'kubernetes', 
			containers: [
			  containerTemplate(name: 'jnlp', image: 'registry.cn-shenzhen.aliyuncs.com/k-spe/dvp-jnlp', alwaysPullImage: true, args: '${computer.jnlpmac} ${computer.name}'),
			  containerTemplate(name: 'git', image: 'alpine/git', alwaysPullImage: true, command: 'cat', ttyEnabled: true),
			  containerTemplate(name: 'tpl', image: 'registry.cn-shenzhen.aliyuncs.com/infrastlabs/alpine-ext:weak', alwaysPullImage: true, command: 'cat', ttyEnabled: true),
			  containerTemplate(name: 'maven', image: 'registry.cn-shenzhen.aliyuncs.com/k-spe/dvp-maven', alwaysPullImage: true, command: 'cat', ttyEnabled: true),
              //containerTemplate(name: 'docker', image: 'registry.cn-shenzhen.aliyuncs.com/k-spe/dvp-docker', alwaysPullImage: true, command: 'cat', ttyEnabled: true),
			  containerTemplate(name: 'docker', image: 'registry.cn-shenzhen.aliyuncs.com/k-spe/dvp-buildah:v4', alwaysPullImage: true, command: 'cat', ttyEnabled: true, privileged: true),
              containerTemplate(name: 'kubectl', image: 'lachlanevenson/k8s-kubectl:v1.10.2', command: 'cat', ttyEnabled: true)
			],
          volumes: [
				//hostPathVolume(hostPath: '/root/.kube', mountPath: '/root/.kube'),
				//persistentVolumeClaim(claimName: 'jenkins-jk-ci-data', mountPath: '/opt/jk_ci_data') //, readOnly: true
				//persistentVolumeClaim(claimName: 'jenkins-shell', mountPath: '/opt/shell'),
				hostPathVolume(hostPath: '/data1/maven_vol/buildah_var_lib_containers', mountPath: '/var/lib/containers'),
				// hostPathVolume(hostPath: '/data1/maven_vol/.m2', mountPath: '/root/.m2'),
				hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock'),
				hostPathVolume(hostPath: '/data1/maven_vol/opt_jk_ws', mountPath: '/opt/jk_ws')
            ],
          imagePullSecrets: [ 'regsecret' ],
          idleMinutes: 600,
          annotations: [
				podAnnotation(key: "sidecar.istio.io/inject", value: "false")
           ]
    ) { this.onemallStages(vlabel, module) }
}